<template>
  <div class="app-container">
    <!--搜索组件-->
    <el-form ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--功能按钮组件-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>
    <!--表格组件-->
    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="编号" width="100"/>
      <el-table-column prop="name" label="商品名称"/>
      <el-table-column prop="coverImg" label="主图" width="350">
        <template #default="scope">
          <div class="cover-img-list">
            <el-image
                v-for="(img, index) in (scope.row.coverImg ? scope.row.coverImg.split(',').filter(Boolean) : [])"
                :key="index"
                :src="img"
                :preview-src-list="(scope.row.coverImg ? scope.row.coverImg.split(',').filter(Boolean) : [])"
                fit="cover"
                style="width: 150px; height: auto; cursor: pointer"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="category1Name" label="一级分类"/>
      <el-table-column prop="category2Name" label="二级分类"/>
      <el-table-column prop="status" label="状态" #default="scope">
        <el-tag v-if="scope.row.status === '0'" type="success">上架</el-tag>
        <el-tag v-else type="danger">下架</el-tag>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" #default="scope" width="220">
        <el-button v-if="scope.row.status == 1" link type="primary" icon="Top"
                   @click="handleUpdateStatus(scope.row.id,0)">上架
        </el-button>
        <el-button v-if="scope.row.status == 0" link type="primary" icon="Bottom"
                   @click="handleUpdateStatus(scope.row.id, 1)">下架
        </el-button>
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
        <el-button link type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[2, 5, 10, 20]"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 新增/修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-steps :active="activeStep" finish-status="success" simple class="mb20">
        <el-step title="基本信息"/>
        <el-step title="规格与SKU"/>
      </el-steps>

      <!-- 第一步：基本信息 -->
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          v-show="activeStep === 0"
      >
        <el-form-item label="商品名称" prop="name" style="width: 320px">
          <el-input v-model="form.name" placeholder="请输入商品名称"/>
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryIds">
          <el-cascader
              v-model="form.categoryIds"
              :options="categoryCascaderOptions"
              :props="{ checkStrictly: true, emitPath: true }"
              placeholder="请选择一级/二级分类"
              @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item label="主图" prop="imageUrl">
          <ImageUpload v-model="form.coverImg"/>
        </el-form-item>
      </el-form>

      <!-- 第二步：规格与SKU-->
      <div v-show="activeStep === 1">
        <el-form-item label="选择规格模板">
          <el-select
              v-model="selectedSpecTemplateId"
              placeholder="请选择规格模板"
              @change="onSpecTemplateChange"
              style="width: 300px"
          >
            <el-option
                v-for="item in specTemplateOptions"
                :key="item.id"
                :label="item.specName"
                :value="item.id"
            />
          </el-select>
          <el-alert
              v-if="specTemplateOptions.length === 0"
              title="该分类下暂无规格模板，请先在规格管理中创建"
              type="warning"
              style="margin-top: 10px"
          />
        </el-form-item>

        <!-- SKU 表格 -->
        <el-table
            v-if="skuTable.length > 0"
            :data="skuTable"
            size="small"
            style="margin-top: 16px"
            max-height="400"
        >
          <el-table-column label="规格组合" width="220">
            <template #default="scope">
              {{ scope.row.specText }}
            </template>
          </el-table-column>
          <el-table-column label="缩略图" #default="scope" width="100">
            <el-upload
                class="avatar-uploader"
                :action="imgUpload.url"
                :headers="imgUpload.headers"
                :show-file-list="false"
                accept=".jpg,.jpeg,.png"
                :on-success="(response, uploadFile, fileList) =>handleSkuSuccess(response, uploadFile, fileList, scope.row)">
              <img
                  v-if="scope.row.thumbImg"
                  :src="scope.row.thumbImg"
                  width="100%"
                  class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.price"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
              >
                <template #prefix>
                  <span>￥</span>
                </template>
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="库存" width="150">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.stock"
                  :min="0"
                  controls-position="right"
                  style="width: 100%"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
        <el-button
            v-if="activeStep < 1"
            type="primary"
            @click="nextStep"
        >
          下一步
        </el-button>
        <el-button
            v-else
            type="primary"
            @click="submitForm"
        >
          提交
        </el-button>
        <el-button @click="open = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {ElMessage} from 'element-plus';
import {getToken} from "@/utils/auth.js";
import {
  listProduct,
  getCategoryCascader,
  listByCategoryId,
  saveProduct,
  getProduct,
  updateProduct,
  delProduct,
  updateStatus
} from '@/api/product/product.js';
import ImageUpload from "@/components/ImageUpload/index.vue";

const editingProductId = ref(null); // 新增：记录正在编辑的商品 ID
const {proxy} = getCurrentInstance()
const ids = ref([])
const multiple = ref(true)
// 弹窗控制
const open = ref(false);
const title = ref('');
const activeStep = ref(0);

// 表格与分页
const total = ref(0);
const loading = ref(true);
const productList = ref([]);

// 分类与规格
const categoryCascaderOptions = ref([]);
const specTemplateOptions = ref([]);
const selectedSpecTemplateId = ref(null);

// 表单数据
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined
  },
  form: {
    name: '',
    coverImg: '',
    categoryIds: []
  },
  imgUpload: {
    // 设置上传的请求头部
    headers: {
      Authorization: "Bearer " + getToken()
    },
    // 图片上传的方法地址:
    url: "http://localhost/dev-api/file/upload"
  }
});

const {queryParams, form, imgUpload} = toRefs(data);

// SKU表格
const skuTable = ref([]);
const coverImgList = ref([]);

// 表单引用
const formRef = ref();

// 表单验证规则
const rules = {
  name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
  categoryIds: [{required: true, message: '请选择分类', trigger: 'change'}]
};

// ================== 页面初始化 ==================
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
};

function getList() {
  loading.value = true;

  listProduct(queryParams.value).then(response => {
    productList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 加载分类级联数据
const loadCategoryCascader = () => {
  getCategoryCascader().then(response => {
    categoryCascaderOptions.value = response.data || [];
  });
};

// ================== 按钮操作 ==================
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.name = undefined;
  handleQuery();
}

// 状态操作
function handleUpdateStatus(row, status) {
  updateStatus(row, status).then(res => {
    if (res.code != 200) {
      ElMessage.error('操作失败: ', res);
      return;
    }
    if (status == 1) {
      ElMessage.success('下架成功');
    } else {
      ElMessage.success('上架成功');
    }
    getList();
  }).catch(() => {
    ElMessage.error('操作失败: ', res);
  });
}

function handleAdd() {
  editingProductId.value = null;
  open.value = true;
  title.value = '添加商品';
  activeStep.value = 0;
  // 重置表单
  form.value.name = '';
  form.value.coverImg = '';
  form.value.categoryIds = [];
  coverImgList.value = [];
  specTemplateOptions.value = [];
  selectedSpecTemplateId.value = null;
  skuTable.value = [];
  loadCategoryCascader();
}

// 编辑
function handleUpdate(row) {
  editingProductId.value = row.id;
  // row 一定存在（从表格操作列传入）
  if (!row || !row.id) {
    ElMessage.warning('无效的商品数据');
    return;
  }
  open.value = true;
  title.value = '编辑商品';
  activeStep.value = 0;
  // 重置状态
  specTemplateOptions.value = [];
  selectedSpecTemplateId.value = null;
  skuTable.value = [];
  coverImgList.value = [];
  // 加载商品详情
  getProduct(row.id).then(res => {
    const product = res.data;
    // 基本信息
    form.value.name = product.name;
    form.value.coverImg = product.coverImg || '';
    form.value.categoryIds = [product.category1Id, product.category2Id];
    // 加载分类
    loadCategoryCascader();
    // 加载规格模板
    listByCategoryId(product.category2Id).then(specRes => {
      specTemplateOptions.value = specRes.data || [];
      if (specTemplateOptions.value.length > 0) {
        selectedSpecTemplateId.value = specTemplateOptions.value[0].id;
      }
      // 解析 specValue
      let specList = [];
      try {
        specList = JSON.parse(product.specValue) || [];
      } catch (e) {
        console.warn('specValue 解析失败，使用 SKU 反推');
        specList = generateSpecFromSku(product.productSkuList);
      }

      // 构造 SKU 表格
      const skuMap = {};
      product.productSkuList.forEach(sku => {
        skuMap[sku.skuSpec] = sku;
      });

      const values = specList.map(s => s.valueList);
      const combinations = cartesian(values);
      skuTable.value = combinations.map(combo => {
        const specText = combo.join(' + ');
        const originSku = skuMap[specText] || {};
        return {
          specText,
          skuSpec: specText,
          thumbImg: originSku.thumbImg || '',
          price: originSku.price || 0,
          stock: originSku.stock || 0,
          saleNum: originSku.saleNum || 0,
          stockNum: originSku.stock || 0,
          id: originSku.id
        };
      });
    });
  }).catch(err => {
    ElMessage.error('加载商品详情失败: ', err);
    open.value = false;
  });
}

// 删除
function handleDelete(row) {
  const productIds = row.id || ids.value
  if (!productIds) {
    ElMessage.warning('请选择要删除的商品');
    return;
  }
  proxy.$modal.confirm('是否确认删除编号为"' + productIds + '"的数据项?').then(function () {
    return delProduct(productIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

// 从 SKU 列表反推规格（仅当 specValue 无效时使用）
const generateSpecFromSku = (skuList) => {
  if (!skuList || skuList.length === 0) return [];

  const specs = {};
  skuList.forEach(sku => {
    const parts = sku.skuSpec.split(' + ');
    parts.forEach((part, index) => {
      const key = `规格${index + 1}`; // 无法知道真实 key，只能用占位
      if (!specs[key]) specs[key] = new Set();
      specs[key].add(part.trim());
    });
  });

  return Object.entries(specs).map(([key, valueSet]) => ({
    key,
    valueList: Array.from(valueSet)
  }));
};
// ================== 分步表单逻辑 ==================

// 分类选择变化
const handleCategoryChange = (value) => {
  if (value && value.length === 2) {
    const category2Id = value[1];
    listByCategoryId(category2Id).then(res => {
      specTemplateOptions.value = res.data || [];
      selectedSpecTemplateId.value = null;
      skuTable.value = [];
    }).catch(() => {
      specTemplateOptions.value = [];
      skuTable.value = [];
    });
  } else {
    specTemplateOptions.value = [];
    skuTable.value = [];
  }
};
// 图片上传
const handleSkuSuccess = (response, uploadFile, fileList, row) => {
  console.log(response)
  console.log(uploadFile)
  row.thumbImg = response.data.url
}

// 选择规格模板
const onSpecTemplateChange = (id) => {
  const template = specTemplateOptions.value.find(t => t.id === id);
  if (template?.specValue) {
    try {
      const specObj = JSON.parse(template.specValue); // { "颜色": ["白","黑"], ... }
      const specList = Object.entries(specObj).map(([key, valueList]) => ({
        key,
        valueList
      }));
      generateSkuTableFromSpec(specList);
    } catch (e) {
      console.error('规格解析失败:', e);
      ElMessage.error('规格模板格式错误');
      skuTable.value = [];
    }
  } else {
    skuTable.value = [];
  }
};

// 笛卡尔积工具函数
const cartesian = (arr) => {
  return arr.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())), [[]]);
};

// 根据规格生成 SKU 表格
const generateSkuTableFromSpec = (specList) => {
  const values = specList.map(s => s.valueList);
  const combinations = cartesian(values);
  skuTable.value = combinations.map(combo => {
    const specText = combo.join(' + ');
    return {
      specText,
      skuSpec: specText,
      thumbImg: '',
      price: 0,
      stock: 0,
      saleNum: 0,
      stockNum: 0
    };
  });
};

// // SKU 缩略图上传
// const handleSkuThumbChange = (index, uploadFile) => {
//   const url = URL.createObjectURL(uploadFile.raw);
//   skuTable.value[index].thumbImg = url;
// };

// 下一步
const nextStep = async () => {
  if (activeStep.value === 0) {
    try {
      await formRef.value.validate();
      if (!form.value.categoryIds || form.value.categoryIds.length !== 2) {
        ElMessage.warning('请选择完整的一级和二级分类');
        return;
      }
    } catch {
      return;
    }
  }
  activeStep.value++;
};

// 上一步
const prevStep = () => {
  activeStep.value--;
};

// 提交表单
const submitForm = async () => {
  if (skuTable.value.length === 0) {
    ElMessage.warning('请配置 SKU 信息');
    return;
  }

  const [category1Id, category2Id] = form.value.categoryIds;

  let specValueStr = '[]';
  const template = specTemplateOptions.value.find(t => t.id === selectedSpecTemplateId.value);
  if (template?.specValue) {
    try {
      const specObj = JSON.parse(template.specValue);
      const specArray = Object.entries(specObj).map(([key, valueList]) => ({
        key,
        valueList
      }));
      specValueStr = JSON.stringify(specArray);
    } catch (e) {
      /* fallback to current specList if needed */
    }
  } else {
    // 如果没有选模板，尝试从当前 SKU 表格反推（不推荐，仅兜底）
    const specKeys = skuTable.value[0]?.specText.split(' + ').map((_, i) => `规格${i + 1}`);
    const specMap = {};
    specKeys.forEach(key => specMap[key] = new Set());
    skuTable.value.forEach(sku => {
      const parts = sku.skuSpec.split(' + ');
      parts.forEach((part, i) => specMap[specKeys[i]].add(part));
    });
    const specArray = Object.entries(specMap).map(([key, set]) => ({
      key,
      valueList: Array.from(set)
    }));
    specValueStr = JSON.stringify(specArray);
  }

  const submitData = {
    id: editingProductId.value, // 编辑时有 ID
    name: form.value.name,
    category1Id,
    category2Id,
    coverImg: form.value.coverImg,
    specValue: specValueStr,
    productSkuList: skuTable.value.map(sku => ({
      id: sku.id, // 保留 SKU ID，用于更新
      skuSpec: sku.skuSpec,
      thumbImg: sku.thumbImg,
      price: sku.price,
      stock: sku.stock,
      saleNum: sku.saleNum,
      stockNum: sku.stock
    }))
  };

  try {
    let apiCall;
    if (submitData.id) {
      // 编辑
      apiCall = updateProduct(submitData);
    } else {
      // 新增
      apiCall = saveProduct(submitData);
    }
    await apiCall;
    ElMessage.success(submitData.id ? '商品更新成功！' : '商品新增成功！');
    open.value = false;
    activeStep.value = 0;
    getList();
  } catch (error) {
    ElMessage.error(submitData.id ? '商品更新失败' : '商品新增失败');
    console.error(error);
  }
};

// ================== 初始化 ==================
getList();
</script>